package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Evaluate;
import com.itheima.reggie.service.EvaluateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/evaluate")
public class EvaluateController {

    @Autowired
    private EvaluateService evaluateService;

    @Cacheable(value = "evaluateCache", key = "#id", unless = "#result == null")
    @GetMapping("/{id}")
    public R<Evaluate> list(@PathVariable Long id) {
        LambdaQueryWrapper<Evaluate> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, Evaluate::getOrderId, id);
        Evaluate evaluate = evaluateService.getOne(lqw);
        if (evaluate != null) {
            return R.success(evaluate);
        }
        return R.error("请评价");
    }

    @CacheEvict(value = "evaluateCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody Evaluate evaluate) {
        log.info("接收的数据evaluate：{}", evaluate);
        if (evaluate.getUserId()==null) {
            //保存用户id
            evaluate.setUserId(BaseContext.getCurrentId());


            //添加数据库
            evaluateService.save(evaluate);

            return R.success("评价保存成功！");
        }
        return R.error("追评成功");
    }

}

